package com.sinosoft.platform.common.util;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.mapper.Mapper;

/**
 * 自定义map converter of xstream
 * 
 * @author fusq
 * @version 1.0
 * @created 30-七月-2010 16:21:53
 */
@SuppressWarnings("unchecked")
public class MapCustomConverter extends AbstractCollectionConverter {

    /**
     * 
     * 方法功能描述
     * 
     * @param mapper
     *      参数
     */
    public MapCustomConverter(Mapper mapper) {
        super(mapper);
    }

    /**
     * 
     * 方法功能描述
     * 
     * @param type
     *      参数
     * @return boolean
     */
    @Override
    public boolean canConvert(Class type) {
        return type.equals(HashMap.class) || type.equals(Hashtable.class)
                || type.getName().equals("java.util.LinkedHashMap") || type.getName().equals("sun.font.AttributeMap");
    }

    /**
     * 
    * 方法功能描述
    * 
    * @param source
    *       参数
    * @param writer
    *       参数
    * @param context
    *       参数
     */
    @Override
    public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
        Map map = (Map) source;
        for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) {
            Entry entry = (Entry) iterator.next();
            writer.startNode(entry.getKey() == null ? "null" : entry.getKey().toString());
            writer.setValue(entry.getValue() == null ? "" : entry.getValue().toString());
            writer.endNode();
        }
    }

    /**
     * 
    * 方法功能描述
    * 
    * @param reader
    *       参数
    * @param context
    *       参数
    * @return Object
     */
    @Override
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
        Map map = (Map) createCollection(context.getRequiredType());
        populateMap(reader, context, map);
        return map;
    }

    /**
     * 
      * 方法功能描述
      * 
      * @param reader
      *         参数
      * @param context
      *         参数
      * @param map 
      *         参数
     */
    protected void populateMap(HierarchicalStreamReader reader, UnmarshallingContext context, Map map) {
        while (reader.hasMoreChildren()) {
            reader.moveDown();
            Object key = reader.getNodeName();
            Object value = reader.getValue();
            map.put(key, value);
            reader.moveUp();
        }
    }
}
